import _ from 'lodash'
import { construct, destruct } from './json-tree'
//去除树形结构中所有systype===1的节点
export const getAllNode = function (array, weight = 1) {
  if (!weight) {
    array.forEach((item) => {
      if (item.children && item.children.length > 0) {
        const newChildren = item.children.filter((i) => i.sysType === 0)
        if (newChildren.length) {
          Object.assign(item, {
            children: newChildren
          })
          getAllNode(item.children)
        } else {
          delete item.children
        }
      }
    })

    return array
  } else {
    let result = construct(array, {
      pid: 'pid', // 展开后的父节点 id 名称
      children: 'children' // 子节点名称
    })
    let arr = []
    result.forEach((item) => {
      if (item.sysType == 0) {
        arr.push(item)
      }
    })
    return arr
  }
}
//去除树形结构中所有systype===1的节点
export const getAllNodeType = function (array) {
  // if (array.sysType !== 0) {
  //     return
  // } else {

  array.forEach((item) => {
    if (item.children && item.children.length > 0) {
      const newChildren = item.children.filter((i) => i.type === 0)
      if (newChildren.length) {
        Object.assign(item, {
          children: newChildren
        })
        getAllNode(item.children)
      } else {
        delete item.children
      }
    }
  })

  return array
  // }
}
export const deleteAllNodeIsShow = function (array) {
  array.forEach((item) => {
    if (item.children && item.children.length > 0) {
      const newChildren = item.children.filter((i) => i.isShow === 1)
      if (newChildren.length) {
        Object.assign(item, {
          children: newChildren
        })
        deleteAllNodeIsShow(item.children)
      } else {
        delete item.children
      }
    }
  })

  return array
}

//判断两个对象是否相等
export const deepCompare = function (o1, o2) {
  var props1 = Object.getOwnPropertyNames(o1)
  var props2 = Object.getOwnPropertyNames(o2)
  if (props1.length != props2.length) {
    return false
  }
  for (var i = 0, max = props1.length; i < max; i++) {
    var propName = props1[i]
    if (o1[propName] !== o2[propName]) {
      return false
    }
  }
  return true
}

//遍历树形数据组合成一个新的数组
export function filterTreeData(treearr, uploaddata) {
  if (treearr.constructor === Array) {
    treearr.forEach((item) => {
      if (item.isUser === true) {
        uploaddata.push({
          id: item.id,
          organizeId: item.pid
        })
      } else {
        if (item.children && item.children.length > 0) {
          filterTreeData(item.children, uploaddata)
        }
      }
    })
  } else {
    return '需要传入数组'
  }
}
//树形数据转普通数组
export function filterTreeList(data) {
  let result = destruct(data, {
    pid: 'pid', // 展开后的父节点 id 名称
    children: 'children' // 子节点名称
  })

  return result
}
//普通数组转树形数据
export function filterListTree(data) {
  let result = construct(data, {
    pid: 'pid', // 展开后的父节点 id 名称
    children: 'children' // 子节点名称
  })

  return result
}
// 给树形数据当前项以及所有子项添加type属性为9
export function isShowTreeItem(data, loginOrganizationId) {
  if (data.constructor === Array) {
    data.forEach((item) => {
      if (item.id === loginOrganizationId) {
        item.Istype = 9
        if (item.children && item.children.length > 0) {
          isShowTreeItemType(item.children, 9)
        }
      } else {
        if (item.children && item.children.length > 0) {
          isShowTreeItem(item.children, loginOrganizationId)
        }
      }
    })
  }
}
// 给树形数据所有项添加type属性为8
export function isShowTreeItemType(treeList, type) {
  if (treeList.constructor === Array && type.constructor === Number) {
    treeList.forEach((item) => {
      item.Istype = type
      if (item.children && item.children.length > 0) {
        isShowTreeItemType(item.children, type)
      }
    })
  }
}

export function filterTree(Treedata) {
  if (Treedata.constructor === Array) {
    Treedata.forEach((item) => {
      if (item.children && item.children.length > 0) {
        filterTree(item.children)
      } else {
        item.id = item.pid + '-' + item.id
      }
    })
    return Treedata
  } else {
    return '需传入一个数组'
  }
}
export function filterTreeOpenList(arr, openlist) {
  if (arr.constructor === Array) {
    arr.forEach((item) => {
      openlist.push(item.routeUrl)
      if (item.children && item.children.length > 0) {
        filterTreeOpenList(item.children, openlist)
      }
    })
    return openlist
  } else {
    return '需传入一个数组'
  }
}
// 清空对象属性值两边空格
export function clearSpace(obj) {
  if (obj.constructor == Object) {
    for (const key in obj) {
      if (obj[key]?.constructor == String) {
        obj[key] = obj[key].trim()
      }
    }

    return obj
  } else {
    return '需要传入一个对象'
  }
}
//保存当前树形结构打开的节点
export function getTreeObjHanlder(obj, arr, boolean, name) {
  if (arr.constructor === Array) {
    //当前是展开
    if (boolean) {
      if (arr && arr.length > 0) {
        if (arr.indexOf(obj.id) === -1) {
          arr.push(obj.id)
        }
      } else {
        arr.push(obj.id)
      }
    }
    //当前是关闭
    else {
      if (arr && arr.length > 0) {
        if (arr.indexOf(obj.id) !== -1) {
          arr.forEach((item, index) => {
            if (item === obj.id) {
              arr.splice(index, 1)
            }
          })
        }
      } else {
        arr = []
      }
    }
    return arr
  } else {
    arr = []
  }
}
//排序
export function compare(property) {
  return function (a, b) {
    var value1 = a[property]
    var value2 = b[property]
    return value1 - value2
  }
}
//筛选树形数据
export function filterTreeHandler(tree, id) {
  if (tree.constructor === Array) {
    tree.filter((item) => {
      if (item.id == id) {
        return item
      } else {
        if (item.children && item.children.length > 0) {
          filterTreeHandler(item, id)
        }
      }
    })
  } else {
    console.error('需要传入一个数组')
  }
}
//过滤数组对象
export function arrayInFilter(brands, fun) {
  return _.filter(brands, fun)
}
/**
 * 生成全局唯一标识符 guid
 * @returns {string}
 */
export function guid() {
  const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  // 因为第一个字符为数值时,该 guid 不能用作 id 或者 class 所以前面加个 guid 前缀
  return `guid${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`
}
//在页面流转中分发单位时的"选人组件"中格式化选人数据
export function peopleChoicePerson(data, resource = 'sysViewDutyVoList', prefix) {
  data.forEach((item, index) => {
    item.nodeId = prefix ? prefix + '-' + item.id : item.id
    item.id = guid()

    //如果是资源===>岗位
    if (resource === 'sysViewDutyVoList' && item[resource] && item[resource].length > 0) {
      //递归处理
      peopleChoicePerson(item[resource], 'sysOverall', item.nodeId)
      //把资源的子级设置为children
      item.children = item[resource]

      delete item[resource]
      item.type = 1
    }
    //如果是岗位===>人员
    if (resource === 'sysOverall' && item[resource] && item[resource].length > 0) {
      //递归处理
      peopleChoicePerson(item[resource], '', item.nodeId)
      //把资源的子级设置为children
      item.children = item[resource]
      delete item[resource]
      item.name += '(岗位)'
      item.type = 1
    }
    //如果是人员
    if (item.overallRealName) {
      item.userId = item.overallUserID
      item.name = item.overallRealName
      item.composeName = item.overallOrganizeName + '-' + item.overallDutyName + '-' + item.overallRealName //人员的详细结构(组织名称-岗位名称-人员名称)
      item.type = 2
    }
  })
  return data
}

export function filterTreeHandeler(tree) {
  if (tree.constructor === Array) {
    tree.forEach((item) => {
      if (item.overallRealName) {
        item.name = item.overallRealName
        item.id = item.overallUserID
        item.usertype = 2
        item.sysOrganizeType = item.overallOrganizeType
        // item.disabled=false
      } else {
        item.usertype = 1
        // item.disabled=true
      }
      item.webid = item.id + '-' + item.overallDutyId + '-' + item.overallOrganizeType

      if (item.children && item.children.length > 0) {
        filterTreeHandeler(item.children)
      } else {
        if (item.formType == 2) {
          item.children = [
            {
              name: '暂无人员'
            }
          ]
        }
      }
    })
    return tree
  } else {
    return '需传入一个数组'
  }
}

//转树

const DEFAULT_CONFIG = {
  id: 'id',
  children: 'children',
  pid: 'pid'
}
const getConfig = (config) => Object.assign({}, DEFAULT_CONFIG, config)
/**
 * 列表结构转树结构
 * @param {array} list 列表数据
 * @param {object} config 键名配置
 * @returns
 */
export function toTree(list, config = {}) {
  config = getConfig(config)
  const nodeMap = new Map(),
    result = [],
    { id, children, pid } = config
  // 第一遍循环使用对象将每项添加一个 children
  for (const node of list) {
    node[children] = node[children] || []
    nodeMap.set(node[id], node)
  }
  // 第二遍循环将【每项放到对应的父级下】，如果没有则父级放到result
  for (const node of list) {
    const parent = nodeMap.get(node[pid])
    if (parent) {
      parent[children].push(node)
    } else {
      result.push(node)
    }
  }
  return result
}
